package com.firewolf.hibernate.relationship.one_many.main;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.firewolf.hibernate.relationship.one_many.dto.Customer;
import com.firewolf.hibernate.relationship.one_many.dto.Order;

public class MainDriver {

	private SessionFactory factory;

	private Session session;

	private Transaction transaction;
	
	@Test
	public void delete(){
		openSession();
		Customer c = (Customer) session.get(Customer.class, 1);
		session.delete(c);
		
		closeSession();
	}
	
	@Test
	public void saveCustomer(){
		openSession();
		
		Customer cus = new Customer();
		cus.setCustomerName("孙悟空");
		
		Set<Order> orders = new HashSet<>();
		Order e = new Order("Order001");
		orders.add(e);
		Order e2 = new Order("Order002");
		orders.add(e2);
		cus.setOrders(orders);
		session.save(cus);
		session.save(e);
		session.save(e2);
		
		closeSession();
	}
	
	private void openSession() {
		session = factory.openSession();
		transaction = session.beginTransaction();
	}
	
	private void closeSession() {
		transaction.commit();
		session.close();
	}

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure("one2many.xml");

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}
}
